package gui.config;

import java.awt.Dimension;
import java.awt.Point;
import java.util.Date;

import interfaces.View;

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import control.Values;

import tryout.DateComperator;
import util.EventTableModel;
import xml.XMLWorker;

public class EventTable extends JTable implements View {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	DetailEditor detailEditor = null;
	XMLWorker worker = null;
	private String filter = null;
	private TableRowSorter<EventTableModel> sorter = null;
	RowFilter<EventTableModel, Object> rf = null;
	EventTableModel model = null;
	
	public EventTable() {
		this.worker = Values.getWorker();
		this.detailEditor = Values.getDetailEditor();
		this.setSize(new Dimension(450, 80));
		this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		this.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent e) {
		        if (e.getValueIsAdjusting()) {
		            return;
		        }
				int row = getSelectedRow();
				if(row>=0){
					int id = Integer.valueOf(getValueAt(row, 0).toString());
					detailEditor.showEvent(worker.getEventByID(id));
				}
			}
		});
		
		model = new EventTableModel(worker.getEvents(), worker.getTableTitles());
		this.setModel(model);
	}

	@Override
	public void refresh() {
		this.setModel(new EventTableModel(worker.getEvents(), worker.getTableTitles()));
		getColumnModel().getColumn(0).setPreferredWidth(33);
		getColumnModel().getColumn(1).setPreferredWidth(74);
		getColumnModel().getColumn(2).setPreferredWidth(71);
		getColumnModel().getColumn(3).setPreferredWidth(280);
		this.repaint();
	}

	public void setFilter(String f, int row) {
		if(f.compareTo(XMLWorker.ALLE)!=0) {
			sorter = new TableRowSorter<EventTableModel>((EventTableModel)getModel());
			setRowSorter(sorter);
	        try {
	            rf = RowFilter.regexFilter(f, row);
	        } catch (java.util.regex.PatternSyntaxException e) {
	            return;
	        }
	        sorter.setRowFilter(rf);
		} else {
			setRowSorter(null);
		}
        refresh();
	}

}
